package com.zsj.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zsj.entity.WebResponse;
import com.zsj.enums.ErrorCodeEnum;
import com.zsj.enums.OrderStatusEnum;
import com.zsj.exception.BusinessException;
import com.zsj.mysql.entity.DyMobileRecharge;
import com.zsj.mysql.service.IDyMobileRechargeService;
import com.zsj.service.NotifyDyService;
import com.zsj.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Description:
 * @Author:
 * @Date:
 */
@RestController
@RequestMapping("/compensate")
@Slf4j
public class CompensateController {

    @Autowired
    private NotifyDyService notifyDyService;

    @Autowired
    private IDyMobileRechargeService mobileRechargeService;

    @PostMapping(value = "/notifyDyBatch")
    public WebResponse notifyDyBatch(@RequestParam(value = "month", required = false) String month) {
        log.info("[补偿]手工触发批量重新回调抖音");
        try {
            if (StringUtils.isBlank(month)) {
                month = DateUtil.getCurrentMonth();
            }
            log.info("月份:{}", month);
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime fiveMinutesAgo = now.minusMinutes(5);
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String lastTime = fiveMinutesAgo.format(formatter);
            List<DyMobileRecharge> list = mobileRechargeService.getNeedNotify(month, lastTime, null);
            log.info("待补偿的数据量:{}", list.size());
            list.forEach(record -> notifyDyService.notifyDy(record, 1));
            return WebResponse.success();
        } catch (Exception e) {
            log.info("[补偿]手工触发批量重新回调抖音异常", e);
            return WebResponse.fail(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }

    @PostMapping(value = "/notifyDySingle")
    public WebResponse customer(@RequestParam("channelChargeNo") String channelChargeNo) {
        log.info("[补偿]手工触发单笔回调抖音, 订单号:{}", channelChargeNo);
        QueryWrapper<DyMobileRecharge> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("channel_charge_no", channelChargeNo);
        DyMobileRecharge record = mobileRechargeService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(record)) {
            log.info("当前月份表未查得，查询上月分表");
            // 默认查询当月的，如果下单是在月末最后一天，查询是在下个月，则此时查不到元交易，需要在上一个月的分表中查询
            record = mobileRechargeService.getBySelfOrderNo(DateUtil.getLastMonth(), channelChargeNo);
            if (ObjectUtils.isEmpty(record)) {
                log.info("根据订单号{}未查询到订单", channelChargeNo);
                throw new BusinessException(ErrorCodeEnum.ORDER_NOT_EXIST);
            }
        }
        if (!OrderStatusEnum.isFinal(record.getOrderStatus() + "")) {
            log.info("订单{}不为终态,无法通知客户,直接返回", channelChargeNo);
            throw new BusinessException(ErrorCodeEnum.PARAM_ERROR);
        }
        boolean flag = notifyDyService.notifyDy(record, 1);
        if (flag) {
            log.info("[补偿]手工触发单笔回调抖音成功");
            return WebResponse.success();
        } else {
            log.info("[补偿]手工触发单笔回调抖音失败");
            return WebResponse.fail(ErrorCodeEnum.SUPPLIER_FAIL);
        }
    }
}
